package com.controller;


import com.config.Result;
import com.dao.StudentinfoDao;
import com.dao.UserDao;
import com.pojo.StudentInfo;
import com.pojo.User;
import com.service.impl.StudentInfoServiceImpl;
import com.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/StuInfo")
public class SelfUserController {

    @Autowired
    UserServiceImpl userService;

    @Autowired
    StudentInfoServiceImpl studentInfoService;

    @PostMapping("/updateInfo")
    public Result<?> updateInfo(@RequestBody User user){

        User usercheck = userService.findBySno(user.getStudentInfo().getSno());

        if (usercheck != null){
            if (!usercheck.getUsername().equals(user.getUsername())){
                return Result.error("-1","该学号已被注册");
            }
        }

        User temporayUser = userService.selectByUsername(user);


        if (temporayUser == null){
            StudentInfo studentInfo = user.getStudentInfo();

            int i = studentInfoService.insertInfo(studentInfo);

            if (i == 1){
                int i1 = userService.updateSno(user.getStudentInfo().getSno(),user.getUsername());
                if (i1 == 1){
                    User currentUser = userService.selectByUsername(user);
                    return Result.success(currentUser);
                }else {
                    return Result.error("-1","更新失败");
                }
            }else {
                return Result.error("-1","更新失败");
            }
        }else {

            int i = userService.updateInfo(user);

            if (i != 0){
                User currentUser = userService.selectByUsername(user);

                return Result.success(currentUser);
            }else {
                return Result.error("-1","更新失败");
            }
        }
    }
}
